package core;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * Created by zhangsen on 2016/10/25.
 */
public class Dispatcher implements Filter{

    private Map<String, DispatcherMapping> map;
    private String jspPath="/";

	public void init(FilterConfig filterConfig) throws ServletException {

        ServletContext context=filterConfig.getServletContext();
        String mappingFile="mapping.xml";
        if(StringUtils.isNotBlank((String)context.getInitParameter("mappingXml")))
        {
            mappingFile=(String)context.getInitParameter("mappingXml");
        }
        if(StringUtils.isNotBlank((String)context.getInitParameter("jspPath")))
        {
            jspPath=(String)context.getInitParameter("jspPath")+"/";
        }
        MappingConfig mappingConfig = new MappingConfig();
		map = mappingConfig.readMappingByXml(mappingFile);

	}

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;

        if(map.containsKey(request.getServletPath())){
            DispatcherMapping mapping=map.get(request.getServletPath());
            Class clazz=mapping.getMappingClass();
            Method method=mapping.getMappingMethod();
            String result=ControllerCaller.callMethod(request,(HttpServletResponse)servletResponse,clazz,method);
            if(null !=result)
            {
                request.getRequestDispatcher(jspPath+result).forward(servletRequest,servletResponse);
            }

        }

    }

    public void destroy() {

    }

}
